package com.laowang.common.utils.security;

import java.security.MessageDigest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Md5加密方法
 * 
 * @author laowang
 */
public class Md5Utils
{
    private static final Logger log = LoggerFactory.getLogger(Md5Utils.class);

    private static byte[] md5(String s)
    {
        MessageDigest algorithm;
        try
        {
            algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(s.getBytes("UTF-8"));
            byte[] messageDigest = algorithm.digest();
            return messageDigest;
        }
        catch (Exception e)
        {
            log.error("MD5 Error...", e);
        }
        return null;
    }

    private static final String toHex(byte hash[])
    {
        if (hash == null)
        {
            return null;
        }
        StringBuffer buf = new StringBuffer(hash.length * 2);
        int i;

        for (i = 0; i < hash.length; i++)
        {
            if ((hash[i] & 0xff) < 0x10)
            {
                buf.append("0");
            }
            buf.append(Long.toString(hash[i] & 0xff, 16));
        }
        return buf.toString();
    }

    public static String hash(String s)
    {
        try
        {
            return new String(toHex(md5(s)).getBytes("UTF-8"), "UTF-8");
        }
        catch (Exception e)
        {
            log.error("not supported charset...{}", e);
            return s;
        }
    }

    public static void main(String[] args) {
        String s = "Api_ID=mixc.imPOSWBJB.GLWXCJB.orderCollect&Api_Version=1.0.0&App_Pub_ID=10000133301US&App_Sub_ID=10000133334PF&App_Token=c7da4d504948465a97ee73d579c30f94&Format=json&Partner_ID=70000006&REQUEST_DATA={\"cashierId\":\"0202a501bhsl113n0101\",\"checkCode\":\"88888888\",\"comments\":\"test\",\"mall\":\"0202A501\",\"mobile\":\"\",\"orderId\":\"HSS0351001100120041010007\",\"store\":\"BHSL113N01\",\"tillId\":\"01\",\"time\":\"20211214095527\",\"totalAmt\":100,\"type\":\"SALE\",\"itemList\":[{\"itemCode\":\"BHSL113N0100\",\"price\":100,\"quantity\":1}],\"payList\":[{\"cardBank\":\"\",\"cardNumber\":\"\",\"discountAmt\":0,\"payAmt\":100,\"paymentMethod\":\"CH\",\"time\":\"20211214095526\",\"value\":100}]}&Sign_Method=md5&Sys_ID=100001333&Time_Stamp=2021-12-14 15:01:36:525&1eba795606524669badeec37a68b4f4e";
        String s1 = hash(s).toUpperCase();
        System.out.println(s1);
        String s2 ="C95A7CC047FEB941C5600E9411856FE0";
    }
}
